package com.warrantyhotel.android.ui;

import java.io.IOException;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import oauth.signpost.OAuth;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.Xml.Encoding;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.News_RSS;
import com.warrantyhotel.android.facebook.Article;
import com.warrantyhotel.android.facebook.DialogError;
import com.warrantyhotel.android.facebook.Facebook;
import com.warrantyhotel.android.facebook.Facebook.DialogListener;
import com.warrantyhotel.android.facebook.FacebookError;
import com.warrantyhotel.android.facebook.Util;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.util.Base64;
import com.warrantyhotel.android.util.BitmapUtils;
import com.warrantyhotel.android.util.BitmapUtils.OnFetchCompleteListener;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import com.warrantyhotel.android.util.ToastUtil;
import com.warrantyhotel.twitter.TwitterUtils;

public class NewsActivityDetail extends Activity implements AsyncQueryListener {

	public static final String APP_ID = "194473333910263";

	private Facebook mFacebook;
	private static String[] PERMISSIONS = new String[] { "offline_access", "read_stream", "publish_stream" };

	private SharedPreferences prefs;
	private final Handler mTwitterHandler = new Handler();
	// private WebView webView;
	private WebView webView;
	private ImageView rss_banner;
	private NotifyingAsyncQueryHandler mHandler;
	private TextView rssTextView;
	private String shortBody = "";
//	private String redirectLink = "";
	private String imageUrl = "";
	private String description = "";

	private final static int TWEET_DIALOG = 234;

	final Runnable mUpdateTwitterNotification = new Runnable() {
		public void run() {
			Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG).show();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_detail);

		this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
		rssTextView = (TextView) findViewById(R.id.rss_title);
		rss_banner = (ImageView) findViewById(R.id.rss_banner);
		webView = (WebView) findViewById(R.id.rss_webView);
		webView.setBackgroundColor(Color.TRANSPARENT);
		String guid = getIntent().getExtras().getString(Keys._guid);
		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
		retrieveNewsRSSbyId(guid);


		try {
			PackageInfo info = getPackageManager().getPackageInfo("com.warrantyhotel.android", PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				Log.i("PXR", Base64.encodeBytes(md.digest()));
			}
		}

		catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void retrieveNewsRSSbyId(String guid) {
		String[] projectionNews = { News_RSS._ID, News_RSS.TITLE, News_RSS.LINK, News_RSS.GUID, News_RSS.DESCRIPTION, News_RSS.LINK_BANNER,
				News_RSS.DATE_UPDATE };
		mHandler.startQuery(QueriesCodes.NEWS_RSS, News_RSS.CONTENT_URI, projectionNews, News_RSS.GUID + " = '" + guid + "'", null, null);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// updateLoginStatus();
	}

	// public void updateLoginStatus() {
	// loginStatus.setText("Logged into Twitter : "
	// + TwitterUtils.isAuthenticated(prefs));
	// }

	public void clearCredential(View view) {
		clearCredentials();
		// updateLoginStatus();
	}

	public void doPlus(View view) {

		boolean isPresentGooglePlusApp = false;
		PackageManager pm = getPackageManager();
		List<ApplicationInfo> packages = pm.getInstalledApplications(Integer.MAX_VALUE);
		for (ApplicationInfo listItem : packages) {
			Log.v("listItem.packageName", listItem.packageName);
			if (listItem.packageName.equals("com.google.android.apps.plus")) {
				isPresentGooglePlusApp = true;
				Intent shareIntent = new Intent(Intent.ACTION_SEND);
				shareIntent.setType("text/plain");
				shareIntent.putExtra(Intent.EXTRA_TEXT, description);
				shareIntent.putExtra(Intent.EXTRA_SUBJECT, shortBody);
				startActivity(Intent.createChooser(shareIntent, "Share with Google +"));
				break;
			}
		}
		if (!isPresentGooglePlusApp) {
			Intent goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.apps.plus"));
			startActivityForResult(goToMarket, 77);
		}

		// ToastUtil.showText(getApplicationContext(), "" + packages.size());
		// final boolean scanAvailable = isIntentAvailable(this,
		// "com.google.zxing.client.android.SCAN");

		// Intent goToMarket = new Intent(Intent.ACTION_VIEW,
		// Uri.parse("market://details?id=com.google.android.apps.plus"));
		// startActivity(goToMarket);
		// Intent shareIntent = new Intent(Intent.ACTION_SEND);
		// shareIntent.setType("text/plain");
		// shareIntent.putExtra(Intent.EXTRA_TEXT,
		// "I want to share this with you!");
		// shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Great Post");
		// startActivity(Intent.createChooser(shareIntent, "Share..."));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.v("asdasdasd", "" + requestCode + " " + resultCode);
		// new LikePostedMessage().execute();
		mFacebook.authorizeCallback(requestCode, resultCode, data);
	}

	public void doTweet(View view) {
		if (TwitterUtils.isAuthenticated(prefs)) {
			// sendTweet();
			showDialog(TWEET_DIALOG);

		} else {
			Intent i = new Intent(getApplicationContext(), com.warrantyhotel.twitter.PrepareRequestTokenActivity.class);
			i.putExtra("tweet_msg", getTweetMsg());
			startActivity(i);
		}
	}

	public void doLike(View view) {
		if (APP_ID == null) {
			Util.showAlert(this, "Warning", "Facebook Applicaton ID must be " + "specified before running this example: see Example.java");
		}
		mFacebook = new Facebook(APP_ID);
		authorizeAndLike(this, new Article());
	}

	// public void sendTweet() {
	// showDialog(TWEET_DIALOG);
	//
	// }

	@Override
	protected Dialog onCreateDialog(int id) {
		LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		switch (id) {
		case TWEET_DIALOG:
			View layout = mInflater.inflate(R.layout.tweet_dialog, null);

			Button twitt = (Button) layout.findViewById(R.id.send_tweet);
			Button clear_credential = (Button) layout.findViewById(R.id.clear_credential);
			clear_credential.setOnClickListener(new android.view.View.OnClickListener() {

				@Override
				public void onClick(View v) {
					clearCredentials();
					dismissDialog(TWEET_DIALOG);
					ToastUtil.showText(getApplicationContext(), getString(R.string.credentials_were_erased));
				}
			});
			twitt.setOnClickListener(new android.view.View.OnClickListener() {

				@Override
				public void onClick(View v) {
					Thread t = new Thread() {
						public void run() {
							try {
								TwitterUtils.sendTweet(prefs, getTweetMsg());
								mTwitterHandler.post(mUpdateTwitterNotification);
							} catch (Exception ex) {
								ex.printStackTrace();
							}
						}
					};
					t.start();
					dismissDialog(TWEET_DIALOG);
				}
			});

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setView(layout);
			builder.setMessage(getString(R.string.tweet_Action));
			builder.setNegativeButton(getString(R.string.cancel), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			builder.setCancelable(true);
			return builder.create();
		default:
			break;
		}
		return null;
	}

	private String getTweetMsg() {
		return shortBody;
		// "I gonna to make my private party with blackjack and hookers "
		// + new Date().toLocaleString();
	}

	private void clearCredentials() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		final Editor edit = prefs.edit();
		edit.remove(OAuth.OAUTH_TOKEN);
		edit.remove(OAuth.OAUTH_TOKEN_SECRET);
		edit.commit();
	}

	// TODO
	private void authorizeAndLike(Activity activity, final Article article) {
		mFacebook.authorize(activity, PERMISSIONS, new DialogListener() {
			@Override
			public void onComplete(Bundle values) {
				Log.v("TAG", "onComplete");
				new LikePostedMessage().execute(article);
			}

			@Override
			public void onFacebookError(FacebookError error) {
				Log.e("TAG", "error", error);
				Toast.makeText(NewsActivityDetail.this, getString(R.string.like_fail), Toast.LENGTH_LONG).show();
			}

			@Override
			public void onError(DialogError e) {
				Log.v("TAG", "onError");
				Toast.makeText(NewsActivityDetail.this, getString(R.string.like_fail), Toast.LENGTH_LONG).show();
			}

			@Override
			public void onCancel() {
				Log.v("TAG", "onCancel");
			}

		});
	}

	private class LikePostedMessage extends AsyncTask<Article, Void, Integer> {
		@Override
		protected Integer doInBackground(Article... params) {
			String response = "";
			Integer code = 0;
			try {
				// TODO
				// final String headLine = "Warranty Hotel";
				// final String shortBody = "Warranty hotel";//
				// article.getAbstractText();
				// final String imageUrl =
				// UrlGenerator.generateImageUrl(article.getPhoto().getUrl(),
				// UrlGenerator.SIZE_SMALL);
				imageUrl = "http://dl.dropbox.com/u/20432838/icon_warranty.png";//
				// article.getPhoto().getUrl();
				// final String redirectLink = "http://google.com";//
				// article.getLink();

				Bundle bundle = new Bundle();
				bundle.putString("message", shortBody);
				bundle.putString("picture", imageUrl);
				bundle.putString("name", "Warranty Hotel");
				bundle.putString("link", imageUrl/* redirectLink */);
				bundle.putString("caption", description);

				response = mFacebook.request("me/feed", bundle, "POST");
				Log.v("FaceBook_Response", response);
				try {
					JSONObject json = new JSONObject(response);
					if (!json.isNull("id")) {
						String id = json.getString("id");
						response = mFacebook.request(id + "/likes", new Bundle(), "POST");
						if (response.equalsIgnoreCase("true")) {
							code = 1;
						}
					}
				} catch (JSONException e) {
					code = 0;
					e.printStackTrace();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
				code = 0;
			} catch (IOException e) {
				e.printStackTrace();
				code = 0;
			}
			return code;
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (result == 1) {
				Toast.makeText(getApplicationContext(), getString(R.string.like_succ), Toast.LENGTH_LONG).show();
			} else if (result == 0) {
				Toast.makeText(getApplicationContext(), getString(R.string.like_succ), Toast.LENGTH_LONG).show();
			}
			super.onPostExecute(result);
		}
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case QueriesCodes.NEWS_RSS:
			if (cursor != null) {
				startManagingCursor(cursor);
				if (cursor.moveToFirst()) {
					String description = cursor.getString(cursor.getColumnIndex(News_RSS.DESCRIPTION));
					webView.loadData(description, "text/html", Encoding.UTF_8.toString());
					// URLImageParser p = new URLImageParser(webView,
					// getApplicationContext());
					// Spanned htmlSpan = Html.fromHtml(description, p, null);
					// webView.setText(htmlSpan);
					// TODO
					String banner_link = cursor.getString(cursor.getColumnIndex(News_RSS.LINK_BANNER));
					BitmapUtils.fetchImage(getApplicationContext(), banner_link, new OnFetchCompleteListener() {

						@Override
						public void onFetchComplete(Object cookie, Bitmap result) {
							rss_banner.setImageBitmap(result);

						}
					});

					String title = cursor.getString(cursor.getColumnIndex(News_RSS.TITLE));
					rssTextView.setText(title);
//					redirectLink = cursor.getString(cursor.getColumnIndex(News_RSS.LINK));
					imageUrl = cursor.getString(cursor.getColumnIndex(News_RSS.LINK));
					description = cursor.getString(cursor.getColumnIndex(News_RSS.DESCRIPTION));
					shortBody = title;
				}
			}
			break;
		}

	}

}